package uk.gov.swmprobation.cplitebase;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.osmdroid.api.IMapController;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import uk.gov.swmprobation.cplitebase.R;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

public class ReviewProjects extends MyActivity {

    ReviewPagerAdapter reviewPagerAdapter;
    ViewPager viewPager;
    static List<Project> projects;
    int position;
    int project_id;
    private BroadcastReceiver backgroundUpdate;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_review_projects);

        setProjects();
        actionBar.hide();
        Bundle extras = getIntent().getExtras();
        position = extras.getInt("position");
        project_id = extras.getInt("project_id");
        
        if(project_id>0){
        	for (int i=0;i<projects.size();i++){
        		if (projects.get(i).getProjectId()==project_id){
        			position = i;
        			break;
        		}
        	}
        }
        
        viewPager.setCurrentItem(position);
        
        backgroundUpdate = new BroadcastReceiver(){

			@Override
			public void onReceive(Context contrext, Intent intent) {
				setProjects();				
				abortBroadcast();
			}
        	
        };
    }
    
    public void onPause(){
    	super.onPause();
    	unregisterReceiver(backgroundUpdate);
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("uk.gov.swmprobation.cpvisibility.event.updatemain");
        intentFilter.setPriority(1);
        registerReceiver(backgroundUpdate, intentFilter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.application_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    public void onCross(View view){
    	int position = viewPager.getCurrentItem();

        final Project projectToDelete = projects.get(position);
        
        final String projectName = projectToDelete.getProjectName();

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to delete "+projectName+"?");
	    builder.setTitle("Delete project?");
		builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   	DatabaseHandler.deleteProject(projectToDelete.getId());      		               
			       		finish();
		           }
		       });
		builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });

		AlertDialog dialog = builder.create();
		dialog.show();
	}
    
    private void setProjects(){
    	projects = DatabaseHandler.getTypeProjects(Project.TYPE_MINE);
    	reviewPagerAdapter = new ReviewPagerAdapter(getSupportFragmentManager());
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(reviewPagerAdapter);
    }
    
    public static class ReviewPagerAdapter extends FragmentStatePagerAdapter {

        public ReviewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            Fragment fragment = new ReviewFragment();
            Bundle args = new Bundle();
            args.putInt(ReviewFragment.ARG_OBJECT, i);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            return projects.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
        	Project project = projects.get(position);
            return Helper.shortName(project.getProjectName());
        }
    }

    public static class ReviewFragment extends Fragment {

        public static final String ARG_OBJECT = "object";

        MyOpenViewMap myOpenMapView;
        IMapController myMapController;
        Project project;
        File thumbnail;
        
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_review_project, container, false);
            Bundle args = getArguments();
            project = projects.get(args.getInt(ARG_OBJECT));
            
            ImageView photoView = (ImageView) rootView.findViewById(R.id.photoview);
            thumbnail = PhotoTools.getThumbnail(project);
            if (thumbnail.exists()){
        		photoView.setImageURI(Uri.fromFile(thumbnail));
        		photoView.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						Intent intent = new Intent();
						intent.setAction(android.content.Intent.ACTION_VIEW);
						intent.setDataAndType(Uri.fromFile(new File(project.getImagePath())), "image/jpg");
						startActivity(intent);
					}
        			
        		});
            }
        	myOpenMapView = (MyOpenViewMap) rootView.findViewById(R.id.openmapview);
        	String tileURL = this.getString(R.string.tileURL);
        	final ITileSource tileSource = new XYTileSource(null, null,
    	            3, 19, 256, ".png", tileURL);
    		myOpenMapView.setTileSource(tileSource);
            myOpenMapView.setBuiltInZoomControls(false);
            myOpenMapView.setClickable(false);
            myMapController = myOpenMapView.getController();
            myMapController.setZoom(17);
            GeoPoint point = new GeoPoint(project.getLat(), project.getLng());
            myMapController.setCenter(point);
            offcenter();
            myOpenMapView.allowScroll=false;
            
            addMarker();
            
            return rootView;
        }
        
        private void offcenter(){
       		myMapController.scrollBy(-50, -50);
        }
        
        private void addMarker(){
    		Drawable markerImage=getResources().getDrawable(R.drawable.cptarget);
            
            markerImage.setBounds(0, 0, markerImage.getIntrinsicWidth(), markerImage.getIntrinsicHeight());
            
            ArrayList<OverlayItem> markerItems = new ArrayList<OverlayItem>();
            
            GeoPoint point = new GeoPoint(project.getLat(), project.getLng());
            
            OverlayItem markerItem = new OverlayItem("Location", "Location of Picture", point);
            markerItem.setMarker(markerImage);
            markerItem.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
            
            markerItems.add(markerItem);
            
            ItemizedIconOverlay<OverlayItem> markerOverlay = new ItemizedIconOverlay<OverlayItem>(MyApplication.getContext(), markerItems, null){
            };

            myOpenMapView.getOverlays().add(markerOverlay);
    	}
        
    }
}

